import  multiprocessing as mu
from multiprocessing import Queue
from multiprocessing import Manager
from data_divd import util
from multiprocessing import Semaphore
def fun1(filename1,QE,semaphore):
    """读取文件"""
    semaphore.acquire()
    print("start processing")
    with open(filename1,"rb") as f:
        res1=f.read()
        QE.put(res1,block=False)
    semaphore.release()
    # 错误示范 QE.append(res1)

def main(*args):
    semaphore = Semaphore(1)
    manager = Manager()
    Q1 = manager.Queue()
    # 错误示范 QE=deque()
    if len(args)<2:
        raise ValueError("参数必须大于2")
    # process=[]
    for item in args:
        p1=mu.Process(target=fun1, args=(item,Q1,semaphore))
        """启动进程"""
        p1.start()
        """在进程2开启前回收进程1,实现按照传参的顺序执行"""
        p1.join()
        # process.append(p1)
    # if kwargs:
    #     for proc in kwargs:
    #         p2 = mu.Process(target=fun1, args=(proc, Q1))
    #         process.append(p2)
    # for p in process:
    #     p.join()

    with open(util.combine_file()+"."+args[0].split(".")[-1],"wb") as f:
        while not Q1.empty():
            data=Q1.get()
            f.write(data)
            print(data)




if __name__ == '__main__':
    import os
    list_to_combine=os.listdir(os.path.join(os.getcwd(),"data_divd"))
    print(list_to_combine)
    for filename in list_to_combine:
        if os.path.join(os.getcwd(), "data_divd",filename).split(".")[-1]=="png":
            print(os.path.join(os.getcwd(), "data_divd",filename))
    res=[os.path.join(os.getcwd(), "data_divd",filename) for filename in list_to_combine if os.path.join(os.getcwd(), "data_divd",filename).split(".")[-1]=="png"]
    # main('top.png', 'bottom.png')
    main(*res[2:])





